"use client";
import { useRouter } from "next/navigation";
import React, { useState } from "react";
import { chatService } from "@/services/api";
import { eventBus } from "@/utils/eventBus";
// import { useSelector } from "react-redux";
import { useAuthhook } from "@/hooks/useAuth";

export default function TalkingPage() {
  const [input, setInput] = useState("");
  const [selectedModel, setSelectedModel] = useState("deepseek-v3");
  const [showModelList, setShowModelList] = useState(false);
  // const userId = useSelector((state: any) => state.auth.userId);
  const { ituser } = useAuthhook();
  const userId = ituser?.userId;
  const router = useRouter();

  // const generateChatId = () => {
  //   const now = new Date();
  //   return now.toISOString().replace(/[^a-zA-Z0-9]/g, "-");
  // };
  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === "Enter" && !e.shiftKey) {
      console.log(e);
      e.preventDefault();
      handleSubmit(e);
    }
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!input.trim()) return;
    // const chatId = generateChatId();
    chatService
      .createChat(userId!, input, { initialMessage: input })
      .then((res) => {
        console.log(res);
        // 触发刷新事件
        // router.push(
        //   `/chat/${res.chat.id}?message=${encodeURIComponent(
        //     input
        //   )}&model=${selectedModel}`
        // );
        router.push(`/chat/${res.chat.id}?&model=${selectedModel}`);
        eventBus.emit("refreshChats");
      });
  };

  return (
    <div className="chat-container">
      <div className="header">
        <h1>新对话</h1>
        <div className="model-selector">
          <button
            onClick={() => setShowModelList(!showModelList)}
            className="model-toggle"
          >
            {selectedModel}
            <span className={`arrow ${showModelList ? "up" : "down"}`}></span>
          </button>
          {showModelList && (
            <ul className="model-list">
              {["deepseek-v3", "deepseek-r1"].map((model) => (
                <li
                  key={model}
                  className={model === selectedModel ? "selected" : ""}
                  onClick={() => {
                    setSelectedModel(model);
                    setShowModelList(false);
                  }}
                >
                  {model}
                </li>
              ))}
            </ul>
          )}
        </div>
      </div>
      <div className="messages-container">
        <div className="messages">
          <div className={"message assistant-message"}>
            您好，有什么可以帮你的吗？
          </div>
        </div>
      </div>
      <form onSubmit={handleSubmit} className="input-form">
        <textarea
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder="输入消息..."
          rows={1}
        />
        <button type="submit">发送</button>
      </form>

      <style jsx>{`
        .messages {
          display: flex;
          flex-direction: column;
          gap: 1rem;
        }

        .message {
          max-width: 80%;
          padding: 1rem;
          border-radius: 1rem;
          word-break: break-word;
        }

        .user-message {
          background: #007bff;
          color: white;
          align-self: flex-end;
        }

        .assistant-message {
          background: #fff;
          border: 1px solid #ddd;
          align-self: flex-start;
        }

        .header {
          padding: 1rem;
          background: #fff;
          border-bottom: 1px solid #e0e0e0;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .model-selector {
          position: relative;
        }

        .model-toggle {
          padding: 0.5rem 1rem;
          border: 1px solid #ddd;
          border-radius: 4px;
          background: #fff;
          cursor: pointer;
          display: flex;
          align-items: center;
          gap: 0.5rem;
        }

        .arrow {
          border: solid #666;
          border-width: 0 2px 2px 0;
          display: inline-block;
          padding: 3px;
          transition: transform 0.2s;
        }

        .arrow.down {
          transform: rotate(45deg);
        }

        .arrow.up {
          transform: rotate(-135deg);
        }

        .model-list {
          position: absolute;
          right: 0;
          top: 100%;
          background: #fff;
          border: 1px solid #ddd;
          border-radius: 4px;
          margin-top: 0.5rem;
          min-width: 150px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .model-list li {
          padding: 0.5rem 1rem;
          cursor: pointer;
          transition: background 0.2s;
        }

        .model-list li:hover {
          background: #f5f5f5;
        }
        .messages-container {
          flex: 1;
          overflow-y: auto;
          padding: 1rem;
        }

        .model-list .selected {
          background: #e3f2fd;
          color: #1976d2;
        }

        .input-form {
          display: flex;
          gap: 1rem;
          padding: 1rem;
          background: #fff;
          border-top: 1px solid #e0e0e0;
        }

        textarea {
          flex: 1;
          padding: 0.8rem;
          border: 1px solid #ddd;
          border-radius: 4px;
          resize: none;
          font-family: inherit;
          font-size: 1rem;
        }

        button[type="submit"] {
          padding: 0.5rem 1.5rem;
          background: #007bff;
          color: white;
          border: none;
          border-radius: 4px;
          cursor: pointer;
          transition: background 0.2s;
        }
      `}</style>
    </div>
  );
}
